from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *


class UserView(APIView):

    def post(self, request):

        ser = UserSer(data=request.data)

        if ser.is_valid():
            ser.save()
            return Response({"msg": "注册成功", "code": 200})
        else:
            return Response({"msg": "注册失败", "code": 400})


class LoginView(APIView):

    def post(self, request):

        username = request.data.get("username")
        password = request.data.get("password")
        user = User.objects.filter(username=username, password=password).first()
        if user:
            return Response({"msg": "登录成功", "code": 200, "uid": user.id})
        else:
            return Response({"msg": "登录失败", "code": 400})


class ClassesView(APIView):

    def get(self, request):
        uid = request.query_params.get("uid")
        if uid:
            grades = Grade.objects.filter(id=User.objects.filter(pk=uid).first().grade_id)
        else:
            grades = Grade.objects.all()
        data_list = []
        for i in grades:
            data = {'grade': GradeSer(i).data}
            classes = Classes.objects.filter(grade_id=i.id)
            data['classes_list'] = ClassesSer(classes, many=True).data
            data_list.append(data)
        return Response(data_list)
